package cn.zhz.controller;


import cn.zhz.entity.*;
import cn.zhz.service.role.RoleService;
import cn.zhz.service.user.UserService;
import cn.zhz.tools.Constants;
import cn.zhz.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    private Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/userlist.html")
    public String getUserList(Model model,
                              @RequestParam(value = "queryname", required = false) String queryUserName,
                              @RequestParam(value = "queryUserRole", required = false) String queryUserRole,
                              @RequestParam(value = "pageIndex", required = false) String pageIndex) {
        logger.info("getUserList ---> queryUserName：" + queryUserName);
        logger.info("getUserList ---> queryUserRole：" + queryUserRole);
        logger.info("getUserList ---> pageIndex：" + pageIndex);

        int _queryUserRole = 0;
        List<User> userList = null;
        //设置页码容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if (queryUserName == null) {
            queryUserName = "";
        }
        if (queryUserRole != null && !queryUserRole.equals("")) {
            _queryUserRole = Integer.parseInt(queryUserRole);
        }
        if (pageIndex != null) {
            currentPageNo = Integer.valueOf(pageIndex);
        }
        //总数量
        int totalCount = userService.getUserCount();
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryUserName, _queryUserRole, currentPageNo, pageSize);
        model.addAttribute("userList", userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "user/userlist";
    }

    /*@RequestMapping(value = "/useradd.html",method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user") User user){
        return "/user/useradd";
    }

    @RequestMapping(value = "/addsave.html",method = RequestMethod.POST)
    public String addUserAdd(User user, HttpSession session){
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if (userService.add(user)){
            return "redirect:/user/userlist.html";
        }
        return "useradd";
    }*/

    @RequestMapping(value = "/add.html", method = RequestMethod.GET)
    public String addUser(@ModelAttribute("user") User user) {
        return "user/useradd";
    }

    @RequestMapping(value = "/add.html", method = RequestMethod.POST)
    public String addSave(User user, HttpSession session, HttpServletRequest request,
                          @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("uploadFile path ============== > " + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("uploadFile oldFileName ============== > " + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                logger.debug("uploadFile prefix============> " + prefix);
                int filesize = 500000;
                logger.debug("uploadFile size============> " + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = path + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = path + File.separator + fileName;
                    }
                    logger.debug("idPicPath: " + idPicPath);
                    logger.debug("workPicPath: " + workPicPath);

                } else {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
            user.setCreationDate(new Date());
            user.setIdPicPath(idPicPath);
            user.setWorkPicPath(workPicPath);
            if (userService.add(user)) {
                return "redirect:/user/userlist.html";
            }
        }
        return "useradd";
    }

    @RequestMapping(value = "/modify.html", method = RequestMethod.GET)
    public String getUserById(@RequestParam int uid, Model model) {
        logger.debug("getUserId uid================" + uid);
        User user = userService.getUserById(uid);
        model.addAttribute(user);
        return "user/usermodify";
    }

    @RequestMapping(value = "/modifysave.html", method = RequestMethod.POST)
    public String modifyUserSave(User user, HttpSession session) {
        logger.debug("modifyUserSave userid==================" + user.getId());
        user.setModifyBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if (userService.modify(user)) {
            return "redirect:/user/userlist.html";
        }
        return "user/usermodify";
    }

    /*@RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String view(@PathVariable int id, Model model){
        logger.debug("view id=============" + id);
        User user = userService.getUserById(id);
        model.addAttribute(user);
        return "user/userview";
    }*/
    @RequestMapping(value = "/view.html", method = RequestMethod.GET)
    @ResponseBody
    public Object view(@RequestParam String id) {
        logger.debug("view id：" + id);
        String cjson = "";
        if (null == id || "".equals(id)) {
            return "nodata";
        } else {
            try {
                User user = userService.getUserById(Integer.valueOf(id));
                cjson = JSON.toJSONString(user);
                logger.debug("cjson：" + cjson);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                return "failed";
            }
        }
        return cjson;
    }

    @RequestMapping(value = "/ucexist.html")
    @ResponseBody
    public Object userCodeIsExit(@RequestParam String userCode) {
        logger.debug("userCodeIsExit userCode：" + userCode);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(userCode)) {
            resultMap.put("userCOde", "exist");
        } else {
            User user = userService.selectUserCodeExist(userCode);
            if (null != user) {
                resultMap.put("userCode", "exist");
            } else {
                resultMap.put("userCode", "noExist");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "/pwdmodify.html", method = RequestMethod.GET)
    public String modifyPwd() {
        return "user/pwdmodify";
    }

    @RequestMapping(value = "/oldPwd.html")
    @ResponseBody
    public Object getPwdByUserId(@RequestParam String oldpassword, HttpSession session) {
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result", "error");
        } else {
            User user = (User) session.getAttribute(Constants.USER_SESSION);
            if (user == null) {
                resultMap.put("result", "sessionerror");
            } else if (!user.getUserPassword().equals(oldpassword)) {
                resultMap.put("result", "false");
            } else {
                resultMap.put("result", "true");
            }
        }
        System.out.println(JSONArray.toJSONString(resultMap));
        return resultMap;
    }

    @RequestMapping(value = "pwdSave", method = RequestMethod.POST)
    public String pwdSave(@RequestParam String newpassword, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER_SESSION);
        Boolean result = userService.updatePwd(user.getId(), newpassword);
        if (result) {
            return "redirect:/login.html";
        } else {
            session.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
        }
        return "user/pwdmodify";
    }

    @RequestMapping(value = "RoleList.html", method = RequestMethod.GET)
    @ResponseBody
    public Object getRoleList() {
        List<Role> roleList = roleService.getRoleList();
        return JSONArray.toJSON(roleList);
    }

    @RequestMapping(value = "delUser.json",method = RequestMethod.GET)
    @ResponseBody
    public Object delUser(@RequestParam String uid) {
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(uid)){
            resultMap.put("delResult","notexist");
        } else {
            Boolean result = userService.deleteUserById(Integer.valueOf(uid));
            if (result) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        return resultMap;
    }
}
